package top.wenzz.commons.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.wenzz.commons.entity.DataEntity;
import top.wenzz.commons.service.BasicService;
import top.wenzz.commons.utils.ExceptionUtils;
import top.wenzz.commons.vo.PageRequest;
import top.wenzz.commons.vo.RetMsg;

/**
 * Created by 钟廷员 on 2016/12/15.
 */
public class BasicCrudController<E extends DataEntity, S extends BasicService> extends BasicController {
    @Autowired
    protected S service;

    @RequestMapping( value = "save", method = RequestMethod.POST )
    public Object save(@RequestBody E entity) {
        String ret = null;
        try {
            ret = service.save(entity);
        } catch (Exception e) {
            ret = ExceptionUtils.getExceptionMsg(e);
        }
        return ret(ret, "保存成功");
    }

    @RequestMapping( value = "update", method = RequestMethod.POST )
    public Object update(@RequestBody E entity) {
        String ret = null;
        try {
            ret = service.update(entity);
        } catch (Exception e) {
            ret = ExceptionUtils.getExceptionMsg(e);
        }
        return ret(ret, "修改成功");
    }

    @RequestMapping( value = "delete/{id}/{version}", method = RequestMethod.DELETE )
    public Object delete(@PathVariable(value = "id") int id, @PathVariable(value = "version") int version) {
        String ret = null;
        try {
            ret = service.delete(id, version);
        } catch (Exception e) {
            ret = ExceptionUtils.getExceptionMsg(e);
        }
        return ret(ret, "删除成功");
    }

    @RequestMapping( value = "pageQuery", method = RequestMethod.POST )
    public Object find(@RequestBody E entity, PageRequest pageRequest) {
        try {
            return RetMsg.success(service.find(entity, pageRequest));
        } catch (Exception e) {
            logger.error("分页查询异常", e);
            return RetMsg.error("系统异常");
        }
    }
}
